package xhwl.retrofitrx.token;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

import com.trello.rxlifecycle.components.RxActivity;

import xhwl.retrofitrx.BaseApi;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

public class TokenUtil {
	private static final String TAG = "TokenUtil";
	private static final String SP_NAME="initial";
	private static final String ACCESS_TOKEN="access_token";
	private static final String LAST_SAVE_TOKEN_TIME="last_save_token_time";


	static SharedPreferences sp=null;
	static{

	}
	/**
	 * 初始化app token
	 * 
	 * @param context
	 * @param callback
	 */
	public static void initToken(final RxActivity context,
			final LoadTokenCallback callback) {
		initToken(context,true,callback);
	}
	/**
	 * 初始化app token
	 *
	 * @param context
	 * @param callback
	 */
	public static void initToken(final RxActivity context,boolean showDialog,
								 final LoadTokenCallback callback) {
		sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
		if (checkLocalToken()) {
			String token = sp.getString(ACCESS_TOKEN,
					null);
			BaseApi.setToken(token);
			if (callback != null) {
				callback.onLoadSuccess(token);
			}
		} else {
			HttpManager.getInstance().dealHttp(context,new TokenApi(showDialog),new OnNextListener<String>(){
				@Override
				public void onNext(String data) {
					if (data != null && data.length() == 40) {
						long currentTime = System.currentTimeMillis();
						Editor edit = sp.edit();
						edit.putLong(LAST_SAVE_TOKEN_TIME,
								currentTime);
						edit.putString(ACCESS_TOKEN, data);
						edit.commit();
						BaseApi.setToken(data);
						if (callback != null) {
							callback.onLoadSuccess(data);
						}
					}
				}
				@Override
				public void onError(HttpException ex) {
					super.onError(ex);
					if (callback != null) {
						callback.onLoadFail(ex.getMessage());
					}
				}
			});
		}
	}
	/**
	 * 检查本地保存的token是否有效
	 * 
	 * @return
	 */
	public static boolean checkLocalToken() {
		String token = sp.getString(ACCESS_TOKEN, null);
		if (token==null||token.length()==0) {
			return false;
		} else {
			long current = System.currentTimeMillis();
			long saveTime = sp.getLong(LAST_SAVE_TOKEN_TIME, 0);
			long duration = current - saveTime;
			Log.d(TAG,"save time=" + saveTime + " current" + current
					+ " duration=" + duration);
			if (duration >=Config.TOKEN_EXPIRY_TIME) {
				return false;
			}
			return true;
		}
	}

}
